package com.sayimo.maker.mall.goods.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sayimo.framework.exception.DaoException;
import com.sayimo.framework.exception.ServiceException;
import com.sayimo.maker.base.dao.impl.BasePhotoInterfaceImplDao;
import com.sayimo.maker.commons.Constant;
import com.sayimo.maker.mall.goods.dao.GoodsCommentInterfaceDao;
import com.sayimo.maker.mall.goods.dao.GoodsListInterfaceDao;
import com.sayimo.maker.mall.goods.dao.GoodsNormsValuesInterfaceDao;
import com.sayimo.maker.mall.goods.dao.GoodsPhotoInterfaceDao;
import com.sayimo.maker.mall.goods.service.GoodsCommentIterfaceService;
import com.sayimo.maker.mall.goods.vo.GoodsComment;
import com.sayimo.maker.mall.goods.vo.GoodsPhoto;
import com.sayimo.maker.mall.orders.dao.OrdersListInterfaceDao;
import com.sayimo.maker.mall.orders.service.OrdersFlowInterfaceService;
import com.sayimo.maker.mall.orders.vo.GenerateOrdersFlowParams;
import com.sayimo.maker.mall.orders.vo.OrdersList;



/**
 * @Project: schoolmallapi
 * @ClassName: GoodsCommentIterfaceImplService
 * @Description: 商品评论service
 * @Author: 曹频辉
 * @Date: 日期：2015年12月28日 时间：下午6:13:34
 * @Version 1.0.0
 */
@Service(value = "goodsCommentIterfaceImplService")
public class GoodsCommentIterfaceImplService implements GoodsCommentIterfaceService {
	private static Log logger = LogFactory.getLog(GoodsCommentIterfaceImplService.class);

	@Autowired
	private GoodsCommentInterfaceDao goodsCommentInterfaceDao;
	@Resource(name = "basePhotoDao")
	private BasePhotoInterfaceImplDao basePhotoDao;
	@Resource(name = "ordersListInterfaceDao")
	private OrdersListInterfaceDao ordersListInterfaceDao;
	@Resource(name = "ordersFlowInterfaceService")
	private OrdersFlowInterfaceService ordersFlowInterfaceService;
	@Resource(name="goodsPhotoDao")
	private GoodsPhotoInterfaceDao goodsPhotoInterfaceDao;
	@Autowired
	private GoodsListInterfaceDao goodsListInterfaceDao;
	@Autowired
	private GoodsNormsValuesInterfaceDao goodsNormsValuesInterfaceDao;

	public GoodsCommentInterfaceDao getGoodsCommentInterfaceDao() {
		return goodsCommentInterfaceDao;
	}

	public void setGoodsCommentInterfaceDao(GoodsCommentInterfaceDao goodsCommentInterfaceDao) {
		this.goodsCommentInterfaceDao = goodsCommentInterfaceDao;
	}

	/**
	 * @Title: queryGoodsComment
	 * @Description: 查询商品评论
	 * @param goodsId
	 * @param recordNum
	 * @throws ServiceException
	 * @return Map
	 */

	@Override
	public Map queryGoodsComment(Integer goodsId, Integer recordNum) throws ServiceException {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			
			List list = goodsCommentInterfaceDao.getGoodsCommentListByGoodsId(goodsId, recordNum);
			if (list != null && list.size() > 0) {

				for (Object o : list) {
					Map temp = (Map) o;
					String[] photoIds = null;
					List<Map<String, Object>> photoUrlList = new ArrayList<>();
					if (temp.get("photoIds") != null && !temp.get("photoIds").equals("")) {
						photoIds = temp.get("photoIds").toString().split(",");
						for (String photoId : photoIds) {
							GoodsPhoto photo = goodsPhotoInterfaceDao.queryGoodsPhotoById(Integer.parseInt(photoId));
							Map<String, Object> mapL = new HashMap<>();
							mapL.put("photoUrl", photo.getPhotoPath());
							photoUrlList.add(mapL);
						}
					}
					if (temp.get("userPhotoUrl") == null) {
						temp.put("userPhotoUrl", "");
					}
					Date createTime = (Date) temp.get("createTime");
					temp.put("createTime", createTime.getTime());
					temp.put("photoUrlList", photoUrlList);
					//查询规格值名称
					Map normList = goodsListInterfaceDao.getAllNormsByGoodsId(goodsId, (Integer)temp.get("normsValueId"));
					if (normList != null) {
						String ids = (String) normList.get("normsValue");
						String[] strings = ids.split(",");
						StringBuffer stringBuffer = new StringBuffer();
						for (int j = 0; j < strings.length; j++) {
							if (!"0".equals(strings[j])) {
								String tempString = goodsNormsValuesInterfaceDao
										.getNormsValueById(Integer.valueOf(strings[j]));
								stringBuffer.append(tempString);
								if (j != (strings.length - 1)) {
									stringBuffer.append(" ");
								}

							}
						}
						temp.put("normsValue", stringBuffer.toString());
					}
					
					
					List replyList = new ArrayList();
					Map firstReply = goodsCommentInterfaceDao.getGoodsCommentReplyById(0, (Integer) temp.get("id"));
					if (firstReply != null) {
						replyList.add(firstReply);
						for (;;) {
							firstReply = goodsCommentInterfaceDao.getGoodsCommentReplyById(
									(Integer) firstReply.get("refId"), (Integer) temp.get("id"));
							if (firstReply == null) {
								break;
							} else {
								replyList.add(firstReply);
							}
						}
					}
					for (Object object : replyList) {
						Map tempObject = (Map) object;

						if (tempObject.get("photoUrl") == null) {
							tempObject.put("photoUrl", "");
						}
						if (tempObject.get("type") == null) {
							tempObject.put("type", "");
						}
						Date refTime = (Date) tempObject.get("refTime");
						tempObject.put("refTime", refTime.getTime());

					}

					temp.put("appendComment", replyList);
				}

				Map statisticsMap = goodsCommentInterfaceDao.getGoodsCommentStatistics(goodsId);
				if (statisticsMap != null) {
					if (statisticsMap.get("goodCommentRate") == null) {
						statisticsMap.put("goodCommentRate", "");
					} else {
						Double goodCommentRate = ((BigDecimal) statisticsMap.get("goodCommentRate")).doubleValue()
								* 100;
						String goodCommentRateStr = goodCommentRate.toString();
						if (goodCommentRateStr.contains(".")) {
							goodCommentRateStr = goodCommentRateStr.substring(0, goodCommentRateStr.indexOf("."));
						}
						goodCommentRateStr += "%";
						statisticsMap.put("goodCommentRate", goodCommentRateStr);
					}
					if (statisticsMap.get("goodComment") == null) {
						statisticsMap.put("goodComment", "");
					}
					if (statisticsMap.get("middleComment") == null) {
						statisticsMap.put("middleComment", "");
					}
					if (statisticsMap.get("negativeComment") == null) {
						statisticsMap.put("negativeComment", "");
					}
					statisticsMap.put("goodsComments", list);
				} else {
					map.clear();
					map.put(Constant.STATUS, Constant.STATUS_ERROR);
					map.put(Constant.ERROR_CODE, Constant.SELECT_ERROR);
					return map;
				}
				map.put(Constant.STATUS, Constant.STATUS_SUCCESS);
				map.put(Constant.DATA, statisticsMap);
			} else {
				map.put(Constant.STATUS, Constant.STATUS_SUCCESS);
				map.put(Constant.DATA, list);
				return map;
			}

		} catch (DaoException de) {
			logger.error(de);
			map.put(Constant.STATUS, Constant.STATUS_ERROR);
			map.put(Constant.ERROR_CODE, Constant.SELECT_ERROR);
			throw new ServiceException(de);
		}
		return map;
	}

	/**
	 * @Title: insertGoodsCommentOrReply
	 * @Description: 添加商品评论或回复
	 * @param goodsComment
	 * @throws ServiceException
	 * @return Map
	 */
	@Override
	public Map insertGoodsCommentOrReply(HttpServletRequest request)
			throws ServiceException {
		Map map = new HashMap();
		GoodsComment goodsComment=new GoodsComment();
		try {
			String createUser = request.getParameter("createUser");
			String ordersId = request.getParameter("ordersId");
			String commentLevel = request.getParameter("commentLevel");
			String commentContent = request.getParameter("commentContent");
			String type = request.getParameter("type");
			
			String goodsId = request.getParameter("goodsId");
			String photoIds = request.getParameter("photoIds");	
			String commentId = request.getParameter("commentId");
			String refId = request.getParameter("refId");
			
			
			goodsComment.setCreateUser(Integer.valueOf(createUser));
			goodsComment.setOrdersId(Integer.valueOf(ordersId));
			goodsComment.setCommentLevel(Integer.valueOf(commentLevel));
			goodsComment.setCommentContent(commentContent);
			goodsComment.setType(Integer.valueOf(type));

			if (goodsId != null && !"".equals(goodsId)) {
				goodsComment.setGoodsId(Integer.valueOf(goodsId));
			}
			if (photoIds != null && !"".equals(photoIds)) {
				goodsComment.setPhotoIds(photoIds);
			}
			if (commentId != null && !"".equals(commentId)) {
				goodsComment.setCommentId(Integer.valueOf(commentId));
			}
			if (refId != null && !"".equals(refId)) {
				goodsComment.setRefId(Integer.valueOf(refId));
			}
			
			Integer result = goodsCommentInterfaceDao.addGoodsCommentOrReply(goodsComment);
			if (result > 0) {
				
				Map tempMap = new HashMap();
				tempMap.put(Constant.MSG, "添加成功");
				map.put(Constant.STATUS, Constant.STATUS_SUCCESS);
				map.put(Constant.DATA, tempMap);
				
				// 判断订单下是否所有商品都已经评论
				int count = goodsCommentInterfaceDao.getNotCommentCntGoodsInOrder(goodsComment);
				if (count != 0) { // 订单下还有商品未评论
					return map;
				}
				
				
					
				GenerateOrdersFlowParams generateOrdersFlowParams = new GenerateOrdersFlowParams(
						goodsComment.getOrdersId(), goodsComment.getCreateUser(), 7);
				OrdersList ordersList = new OrdersList();
				ordersList.setId(goodsComment.getOrdersId());
				ordersList.setStatus(7);
				ordersListInterfaceDao.updateOrdersList(ordersList);
				ordersFlowInterfaceService.insertOrdersFlow(generateOrdersFlowParams);
				
			} else {
				map.put(Constant.STATUS, Constant.STATUS_ERROR);
				map.put(Constant.ERROR_CODE, Constant.GOODS_COMMENT_ADD_FAIL);
			}
		} catch (DaoException de) {
			logger.error(de);
			throw new ServiceException(de);
		}
		return map;
	}

	/**
	 * 
	 * @Title: canComment @Description: 该用户是否可对该商品评论 @param customerId @param
	 *         goodsId @return @throws ServiceException @return boolean @throws
	 */
	@Override
	public boolean canComment(Integer customerId, Integer goodsId) throws ServiceException {
		boolean result = false;
		try {
			Integer temp = goodsCommentInterfaceDao.getPurchaseTimesByCustomerId(customerId, goodsId);
			if (temp != null && temp > 0) {
				result = true;
			} else {
				result = false;
			}
		} catch (DaoException de) {
			logger.error(de);
			throw new ServiceException(de.getMessage());
		}
		return result;
	}
}
